// pages/seller/person.js
const app = getApp();

let req = require('../../utils/request.js');
let api = require('../../utils/api.js');
let util = require('../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    seller_status: {
      waiting: 'http://p1gruod0l.bkt.clouddn.com/waiting.png',
      success: 'http://p1gruod0l.bkt.clouddn.com/20180607000920729.png',
      fail: 'http://p1gruod0l.bkt.clouddn.com/20180607000920616.png'
    },
    btn_show: '',
    total_price: 0,
    week: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'],
    custom: { country: 'Andorra', code: 'AD', area: "376" },
    reg: null,
    imgs: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载景点信息',
    })
    var _this = this,
        country = util.country,
        id = options.id, token = wx.getStorageSync('user_token')
    
    token = !token ? '' : token;

    _this.setData({country: country});
    req.request(
      api.getProductInfoById,
      { method: 'POST', data: { 'pro_id': id, token: token }},
      function (res) {
        res = res.data
        if (res.status != 1) { 
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        } else {
          var product_info = res.product_info
          console.info(product_info.pro_imgs);
          !product_info.pro_imgs ? (product_info.pro_imgs = [product_info.full_img]) : (product_info.pro_imgs = product_info.pro_imgs.split(','));

          _this.setData({ product_info: product_info, product_id: id })
          wx.hideLoading();
        }

      }
    )
  },

  onShow() {
    let custom = wx.getStorageSync('custom')
    if (custom) {
      this.setData({ custom: custom });
    }
  },

  //用户点击开始预约
  startBooking() {
    //检查当前日期时间
    let _this = this, date = util.getDate(), time = util.getTime(), info = _this.data.product_info, ticket_category = JSON.parse(info.ticket_category), options = JSON.parse(info.options), pricing_type = info.pricing_type, option_id = _this.getOptionId(options), people = [], option_arr = [], min_people = info.min_people, max_people = info.max_people;
    
    //根据价格类型来确定选择人数的地方是什么样子的
    for(let i in ticket_category) {
      let data = {
        id: ticket_category[i]['id'],
        name: ticket_category[i]['name'],
        count: i == 0 ? min_people : 0
      }
      people.push(data);
    }

    //渲染option列表
    for(let i in options) {
      if(options[i].availabilities.length != 0) {
        let data = {
          id: options[i].id,
          name: options[i].name ? options[i].name : 'Option ' + (parseInt(i) + 1)
        }
        option_arr.push(data);
      }
    }

    _this.setData({selected_option_name: option_arr[0].name, people: people, option_arr: option_arr, pricing_type: pricing_type, today: date, selected_date: date, option_id: option_id, min_people: min_people, max_people: max_people, total_people: min_people})

    //获取当前日期时间可用的选项
    _this.checkAvailability(date, time, option_id);
  },

  //计算价格
  countPrice(default_time = 1) {
    if(default_time === '') {
      wx.showToast({
        title: '您选择的当日已无场次',
        icon: 'none'
      });
      this.setData({ disabled: true });
      return;
    }
    let _this = this, 
      option_id = _this.data.option_id, 
      info = _this.data.product_info, 
      options = JSON.parse(info.options), 
      people = _this.data.people, 
      pricing_type = _this.data.pricing_type, 
      selected_date = _this.data.selected_date, 
      target_option, availabilities, 
      useable = [], 
      local_datetime = _this.data.local_datetime, 
      week = _this.data.week;

    //获取当前已选择的option
    for(let i in options) {
      if(options[i].id == option_id) {
        target_option = options[i]
        availabilities = options[i].availabilities
      }
    }
    
    if(!target_option) {  //没有符合条件的选项
      _this.setData({disabled: true});
      console.info(1)
      return;
    }

    let slot_type = target_option.slot_type;
    
    //从当前option中选出日期可用项
    for (let i in availabilities) {
      let start = availabilities[i].start_date, end = availabilities[i].end_date;
      if(selected_date >= start && selected_date <= end) {
        useable.push(availabilities[i]);
      }
    }

    if (useable.length == 0) {  //没有符合条件的选项
      _this.setData({ disabled: true });
      console.info(2)
      return;
    }

    //现在已经拿到时间了 
    // let now = new Date(local_datetime.split(' ')[0]), year = now.getFullYear(), month = now.getMonth() + 1;
    // now.setHours(local_datetime.split(' ')[1].split(':')[0])
    // now.setMinutes(local_datetime.split(' ')[1].split(':')[1])
    // let day = now.getDate(), hour = now.getHours(), minute = now.getMinutes(), today = week[now.getDay()], now_date, now_time, price_data
    // month = month < 10 ? '0' + month : month
    // day = day < 10 ? '0' + day : day
    // hour = hour < 10 ? '0' + hour : hour
    // minute = minute < 10 ? '0' + minute : minute
    // now_time = hour + ':' + minute
    // now_date = year + '-' + month + '-' + day

    // for(let i in useable) {
    //   let option_time = useable[i].times[today]   //拿到相应星期的预定时间
    //   if(option_time.length != 0) {
    //     if (slot_type == 'opening_hours') {
    //       if(selected_date == now_date && now_time < option_time[0][1]) {
    //         price_data = useable[i].prices;
    //       } else if (selected_date != now_date) {
    //         price_data = useable[i].prices;
    //       }else {
    //         continue;
    //       }
    //     } else if (slot_type == 'starting_times') {
    //       if (selected_date != now_date) {
    //         price_data = useable[i].prices;
    //       }else {
    //         if (option_time.length != 1 && now_time < option_time[option_time.length - 1]) {
    //           price_data = useable[i].prices;
    //         } else if (option_time.length == 1) {
    //           price_data = useable[i].prices;
    //         } else {
    //           continue;
    //         }
    //         continue;
    //       }
    //     } else if (slot_type == 'time_range') {
    //       if (selected_date == now_date && now_time < option_time[0][1]) {
    //         price_data = useable[i].prices;
    //       } else if (selected_date != now_date) {
    //         price_data = useable[i].prices;
    //       } else {
    //         continue;
    //       }
    //     }
    //   }else {
    //     continue;  //为空说明今天没有可用选项
    //   }
    // }

    // if(!price_data) {
    //   console.info(useable)
    //   _this.setData({ disabled: true });
    //   return;
    // }
    
    let price_data = useable[0].prices

    let total_price = 0;
    if(pricing_type == 'group_pricing') {
      for(let i in price_data) {
        let count = people[0].count;
        if(count >= price_data[i].min_people && count <= price_data[i].max_people) {
          total_price = price_data[i].price
        }
      }
      people[0].total = total_price
    } else if (pricing_type == 'person_pricing') {
      for(let i in price_data) {
        for(let j in people) {
          if(price_data[i].category == people[j].name) {
            total_price += price_data[i].price * people[j].count;
            people[j].total = price_data[i].price * people[j].count;
          }
        }
      }
    }
    _this.setData({ total_price: total_price, slot_type: slot_type, people: people });
  },

  //检查用户选择的日期是否可用
  checkAvailability(date, time, option_id) {
    wx.showLoading({
      title: '加载中'
    })
    let _this = this, product_info = _this.data.product_info, lat = product_info.ex_lat, lng = product_info.ex_lng, localTimezone = new Date().getTimezoneOffset() / 60, resource = product_info.ex_resource;
    req.request(api.checkAvailability, { data: { date: date, time: time, option_id: option_id, local_timezone: localTimezone, lat: lat, lng: lng, resource: resource } }, function (res) {
      wx.hideLoading();
      res = res.data;
      let target_time = res.target_datetime;
      _this.countingTime(target_time);
      if (res.code != 1) {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        });
        _this.setData({ disabled: true });
      }else {
        let data = res.data, time_arr = [], default_time = _this.getDefaultTime(data);
        for(let i in data) {
          if (data[i].date_time !== '') {
            time_arr.push(data[i].date_time);
          }
        }
        _this.setData({selected_time: default_time, time_arr: time_arr, disabled: false})
        //计算价格
        _this.countPrice(default_time);
      }
      _this.showBox();
    });
  },

  // 获取默认选择的场次
  getDefaultTime(data) {
    let default_time = '';
    for (let i in data) {
      if (data[i].date_time !== '') {
        default_time = data[i].date_time
        break;
      }
    }
    return default_time;
  },

  //开始走时
  countingTime(datetime) {
    let date = datetime.split(' ')[0], time = datetime.split(' ')[1], 
    date_obj = new Date(date), _this = this, local_datetime = _this.data.local_datetime;
    date_obj.setHours(time.split(':')[0])
    date_obj.setMinutes(time.split(':')[1])
    date_obj.setSeconds(time.split(':')[2])
    let timestamp = date_obj.getTime();
    
    if (!local_datetime) {
      let calculated_datetime = util.getDatetime(timestamp);
      _this.setData({ local_datetime: calculated_datetime })
      setInterval(function () {
        timestamp += 1000;
        let calculated_datetime_1 = util.getDatetime(timestamp);
        _this.setData({local_datetime: calculated_datetime_1})
      }, 1000);
    }
  },

  //用户选择人数
  changeCount(e) {
    let _this = this, people = _this.data.people, id = e.currentTarget.id, name = e.currentTarget.dataset.name, min_people = _this.data.min_people, max_people = _this.data.max_people, total_people = parseInt(_this.data.total_people);

    for(let i in people) {
      if(id == people[i].id) {
        people[i].count = parseInt(people[i].count) + (name == 'add' ? 1 : -1);
        total_people += name == 'add' ? 1 : -1;
      }
    }
    _this.setData({total_people: total_people, people: people})
    _this.countPrice();
  },

  //用户更换选项
  changeOption(e) {
    let _this = this, id = e.currentTarget.id, today = _this.data.today, date = _this.data.selected_date, time = date == today ? util.getTime() : '00:00:00', option_arr = _this.data.option_arr, selected_option_name;
    for(let i in option_arr) {
      if(id == option_arr[i].id) {
        selected_option_name = option_arr[i].name;
      }
    }
    _this.setData({ option_id: id, selected_option_name: selected_option_name});
    _this.checkAvailability(date, time, id);
    
    _this.setData({ check_wrapper: '', check_content: '' })
    setTimeout(function () {
      _this.setData({ check_show: '' })
    }, 300);
  },

  //用户调整选项
  selectOptions(e) {
    let name = e.currentTarget.dataset.name, _this = this, value
    switch(name) {
      case 'date':
        value = e.detail.value
        let today = _this.data.today, time = value == today ? util.getTime() : '00:00:00', option_id = _this.data.option_id;
        _this.setData({selected_date: value})
        _this.checkAvailability(value, time, option_id);
        break;
      case 'time':
        value = e.detail.value
        let time_arr = _this.data.time_arr;
        _this.setData({ selected_time: time_arr[value] })
        break;
    }
  },

  //用户选择国家
  changeCountry(e) {
    let id = e.currentTarget.id, country = util.country, area = e.currentTarget.dataset.area, _this = this, custom = _this.data.custom, name = e.currentTarget.dataset.name;

    custom.country = name
    custom.code = id
    custom.area = area

    for (let i in country) {
      if (country[i].area === area) {
        _this.setData({ reg: country[i].reg ? country[i].reg : null });
      }
    }

    _this.setData({ check_wrapper: '', check_content: '', country: country, custom: custom, inputed_country: '' })
    setTimeout(function () {
      _this.setData({ check_show: '' })
    }, 300);
  },

  //用户填写信息
  insertInfo(e) {
    let value = e.detail.value, _this = this, custom = _this.data.custom, name = e.currentTarget.dataset.name
    custom[name] = value
    _this.setData({custom: custom})
  },

  getOptionId(options) {
    let id;
    for(let i in options) {
      if (options[i].availabilities.length != 0) {
        id = options[i].id;
        break;
      }
    }
    return id;
  },
  showBox() {
    let _this = this;
    _this.setData({box_show: 'box-show'})
    setTimeout(function() {
      _this.setData({ box_wrapper: 'wrapper-show', box_content: 'content-show'})
    }, 20);
  },
  showSelect(e) {
    let _this = this, name = e.currentTarget.dataset.name;
    console.info(name);
    _this.setData({ check_show: 'select-show', option_name: name, option_text: name == 'people' ? '选择人数' : name == 'option' ? '选择套餐' : '选择国家' })
    setTimeout(function () {
      _this.setData({ check_wrapper: 'select-wrapper', check_content: 'select-content-show' })
    }, 20);
  },
  search(e) {
    let _this = this, value = e.detail.value, country = util.country, result = []
    if(value != '') {
      for(let i in country) {
        if (country[i].name.toLowerCase().search(value.toLowerCase()) > -1 || country[i].code.toLowerCase().search(value.toLowerCase()) > -1) {
          result.push(country[i])
        }
      }
      _this.setData({ country: result, inputed_country: value });
    }else {
      _this.setData({ country: country, inputed_country: value });
    }
  },
  hideBox(e) {
    let _this = this, name = e.currentTarget.dataset.name;
    if(name == 'check') {
      _this.setData({ box_wrapper: '', box_content: '' })
      setTimeout(function () {
        _this.setData({ box_show: '' })
        _this.prevStep();
      }, 310);
    }else if(name == 'select') {
      _this.setData({ check_wrapper: '', check_content: '' })
      setTimeout(function () {
        _this.setData({ check_show: '' })
      }, 300);
    }
  },
  nextStep() {
    //检查是否登录
    if (!wx.getStorageSync('user_token')) {
      wx.showModal({
        title: '提示',
        content: '您尚未登录，请先至个人中心登录',
        showCancel: true,
        confirmText: '去登录',
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/user/index',
            })
          }
        }
      })
      return;
    }
    
    this.setData({step_1: 'hide', step_2: 'show'})
  },
  prevStep() {
    this.setData({ step_1: '', step_2: '' })
  },
  comfirm() {
    //生成预约订单
    let _this = this, ex_id = _this.data.product_id, option_id = _this.data.option_id, people = _this.data.people, total_price = _this.data.total_price, selected_date = _this.data.selected_date, selected_time = _this.data.selected_time, slot_type = _this.data.slot_type, custom = _this.data.custom, msg = '', flag = false, local_custom = wx.getStorageSync('custom'), diff = true, reg = _this.data.reg;;

    msg = !custom.fullName ? '请填写您的全名' :
      !custom.firstName ? '请填写您的英文名' :
        !custom.lastName ? '请填写您的英文姓' :
          !custom.email ? '请填写您的电子邮箱' :
            !(/^([a-zA-Z0-9._-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/.test(custom.email)) ? '请填写正确的电子邮箱' :
              // !custom.id_card ? '请填写您的身份证号码' :
                // !(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(custom.id_card)) ? '请填写正确的身份证号码' :
                  !custom.phone ? '请填写您的手机号码' :
                    (reg !== null && !reg.test(`+${custom.area}${custom.phone}`)) ? '请填写正确的手机号码' : flag = true;

    if(!flag) {
      wx.showToast({
        title: msg,
        icon: 'none'
      })
      return;
    }

    for(let i in custom) {
      if(custom[i] != local_custom[i]) {
        diff = false;
      }
    }

    if(!diff) {
      wx.showModal({
        title: '提示',
        content: '需要为您自动保存您的用户信息吗？',
        showCancel: true,
        cancelText: '不了',
        confirmText: '好的',
        success: function(res) {
          if(res.confirm) {
            custom.token = wx.getStorageSync('user_token')
            req.request(api.saveUserInfo, {data: custom}, function(res) {
              wx.setStorageSync('custom', custom);
              create();
            })
          }else {
            create();
          }
        },
      })
    }else {
      create();
    }

    function create() {
      wx.showLoading({
        title: '加载中',
      })

      req.request(api.createOrder, {
        data: {
          ex_id: ex_id,
          option_id: option_id,
          people: JSON.stringify(people),
          total_price: total_price,
          date: selected_date,
          time: selected_time,
          slot_type: slot_type,
          first_name: custom.firstName,
          last_name: custom.lastName,
          email: custom.email,
          id_card: custom.id_card,
          phone: custom.phone,
          country_name: custom.country,
          country_code: custom.code,
          user_token: wx.getStorageSync('user_token'),
          area_code: custom.area
        }
      }, function (res) {
        wx.hideLoading();
        res = res.data;
        if (res.code != 1) {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          })
          return;
        } else {
          let order_id = res.data.order_id;
          wx.navigateTo({
            url: 'check?id=' + order_id,
          })
        }
      })
    }
  }
})